package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @desc
 * @author: weili23
 * @params
 * @Date: 2024/4/1 16:48
 * @version: 1.0
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;
    @Resource
    private IBlogService blogService;
    @Override
    public Result queryBlogById(Long id) {
        //根据id获取blog信息
        Blog blog = getById(id);
        if(blog == null){
            return Result.fail("笔记不存在");
        }
        //查询用户信息
        User user = userService.getById(blog.getUserId());
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        //判断用户是否点过赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {
        Long userId = UserHolder.getUser().getId();
        String key = "blog:liked:"+id;
        //1.先判断用户是否点过赞    有set  变成zset = sortedset
        //Boolean ismember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //2.如果用户没点赞
        if(score == null){
            //2.1 数据库点赞数+1
            boolean b = update().setSql("liked=liked+1").eq("id", id).update();
            if(b){
                //2.2 保存点赞的用户到redis中的set集合   有set  变成zset = sortedset   score 赋值 System.currentTimeMillis()
                //stringRedisTemplate.opsForSet().add(key,userId.toString());
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }else{
            //如果已点赞，取消点赞
            //3.1 数据库点赞数-1
            boolean b = update().setSql("liked=liked-1").eq("id", id).update();
            if(b){
                //3.2 移除redis中的set集合中的用户信息  有set  变成zset = sortedset
                //stringRedisTemplate.opsForSet().remove(key,userId.toString());
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        return Result.ok();
    }

    //查询商品点赞的用户信息 查询前五
    @Override
    public Result queryBlogLikes(Long id) {
        String key = "blog:liked:"+id;
        Set<String> top5UserID = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5UserID == null ||top5UserID.isEmpty()){
            return Result.ok(Collections.emptyList());
        }

        //解析出其中的用户iD
        List<Long> ids = top5UserID.stream().map(Long::valueOf).collect(Collectors.toList());
        //这条sql语句 查询出来顺序有问题 是mysql的问题
        //List<User> users = userService.listByIds(ids);
        String idsStr = StrUtil.join(",",ids);
        List<User> users = userService.query().in("id", ids).last("ORDER BY FIELD(id,"+ idsStr+")").list();
        return Result.ok(users);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        User user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (isSuccess) {
            //保存成功后，保存到用户的收件箱 存储到redis集合
            //查询博主的粉丝
            List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
            for (Follow follow : follows) {
                //推送粉丝id
                Long userId = follow.getUserId();
                String key = "feed:"+userId;
                stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
            }

        }else{
            return Result.fail("新增笔记失败");
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryUserOfFollow(Long maxTime, Integer offset) {
        //1.先查询博主推送给用户的blog
        Long userId = UserHolder.getUser().getId();
        String key = "feed:"+userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, maxTime, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        //2.解析数据 blogId  score(minTime)
        int ofs=1;
        long minTime = 0;
        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> tuple: typedTuples) {
            //把blogid存储到list集合中
            Long blogId = Long.valueOf(tuple.getValue());
            blogIds.add(blogId);
            //获取分数（时间戳）
            long time = tuple.getScore().longValue(); //这个循环到最后 一定是最小的分数，就是最小的时间戳
            //便宜量计算  最小分数内相等的
            if(time == minTime){
                ofs++;
            }else{
                ofs=1;
                minTime = time;
            }
        }
        //根据blogid查询blog信息  这条数据返回是无序的
        //List<Blog> blog = blogService.listByIds(blogIds);
        String idsStr = StrUtil.join(",",blogIds);
        List<Blog> blogList = query().in("id", blogIds).last("ORDER BY FIELD(id," + idsStr + ")").list();
        for(Blog blog:blogList){
            //查询用户信息
            User user = userService.getById(blog.getUserId());
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            //判断用户是否点过赞
            isBlogLiked(blog);
        }
        //封装返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(ofs);
        return Result.ok(scrollResult);
    }


    //判断用户是否点过赞,给islike赋值
    private void isBlogLiked(Blog blog){
        User user = UserHolder.getUser();
        //用户为空直接返回  首页没登录点赞的
        if (user == null) {
            return;
        }
        Long userId = user.getId();
        String key = "blog:liked:"+blog.getId();
        //1.先判断用户是否点过赞 有set  变成zset = sortedset
        //Boolean ismember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }
}
